/*******************************************************************************
Copyright (C) 2016 Mestrelab Research S.L. All rights reserved.

This file is part of the Mnova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is
provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN,
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*******************************************************************************/

/*globals Settings*/
/*jslint plusplus: true, indent: 4, white: true, continue: true*/

function TCSPSettingsHandler(aSettingsKey, aDefaultObj)
{
	"use strict";

	var values = {};

	function getValue(aKey, aDefValue)
	{
		if (!aDefValue) {
			aDefValue = aDefaultObj[aKey];
		}

		if (typeof(aDefValue) === "object") {
			return JSON.parse(getValue(aKey, JSON.stringify(aDefValue)));
		}

		var setts = new Settings(aSettingsKey);
		return setts.value(aKey, aDefValue);
	}

	function setValueIfNotEmpty(aKey, aValue, aDefValue)
	{
		if (!aDefValue) {
			aDefValue = aDefaultObj[aKey];
		}

		if (typeof(aValue) === "object") {
			return setValueIfNotEmpty(aKey, JSON.stringify(aValue), JSON.stringify(aDefValue));
		}

		var setts = new Settings(aSettingsKey);

		if (aValue !== undefined && aValue !== null && aValue !== aDefValue) {
			setts.setValue(aKey, aValue);
		} else {
			setts.remove(aKey);
		}
	}

	//read settings
	Object.getOwnPropertyNames(aDefaultObj).forEach(function (aProp) {
		values[aProp] = getValue(aProp);
	});

	//expose the settings as properties that write to registry changes
	Object.getOwnPropertyNames(values).forEach(function (aProp) {
		Object.defineProperty(this, aProp, {
			"get": function() {
				return values[aProp];
			},
			"set": function(aValue) {
				values[aProp] = aValue;
				setValueIfNotEmpty(aProp, aValue);
			}
		});
	}, this);

	//to get a simple js object with the properties
	this.toJSON = function () {
		return JSON.parse(JSON.stringify(values));
	};
}
